import { Application } from 'egg';
import * as pageFindPlugin from 'mongoose-paginate';
import isPositiveInt from '../validator';
import { MemberType, CleanOrderStatus, CleanOrderStatusName, CleanMemberOrderTypeEnums } from '../constants';

/**
 * 保洁会员充值订单集合
 */
export default (app: Application) => {
  const mongoose = app.mongoose;
  const ObjectId = mongoose.Schema.Types.ObjectId;
  const cleanMemberOrderSchema = new mongoose.Schema({
    // 门店Id
    siteId: {
      type: ObjectId,
      required: true,
    },
    // 订单id
    orderId: {
      type: Number,
      required: true,
    },
    // 用户Id
    userId: {
      type: ObjectId,
      required: true,
    },
    // 订单金额
    orderPrice: {
      type: Number,
      required: true,
      validate: isPositiveInt,
    },
    // 会员类型
    memberType: {
      type: Number,
      enum: [ MemberType.reCharge, MemberType.deposit ],
    },
    // 状态
    status: {
      type: Number,
      default: CleanOrderStatus.unPaid,
      enum: [
        CleanOrderStatus.canceled,
        CleanOrderStatus.completed,
        CleanOrderStatus.unPaid,
        CleanOrderStatus.invalid,
      ],
    },
    // 订单类型
    orderType: {
      type: String,
      enum: [
        CleanMemberOrderTypeEnums.cleanMemberRechargeNew,
        CleanMemberOrderTypeEnums.cleanMemberRecharge,
        CleanMemberOrderTypeEnums.cleanMemberNormal,
        CleanMemberOrderTypeEnums.cleanMemberNormalNew,
      ],
      required: true,
    },
    // 订单支付时间
    payTime: {
      type: Date,
      required: false,
    },
    // 订单支付方式
    payWay: {
      type: String,
      required: false,
    },
  }, { timestamps: true, toJSON: { virtuals: true, getters: true } });

  // 状态描述
  // tslint:disable-next-line:ter-prefer-arrow-callback
  cleanMemberOrderSchema.virtual('statusName').get(function (this: any) {
    return CleanOrderStatusName[this.status];
  });

  cleanMemberOrderSchema.index({ siteId: 1 });
  cleanMemberOrderSchema.plugin(pageFindPlugin, {});
  return mongoose.model('Cleanmemberorder', cleanMemberOrderSchema);
};
